package com.k.kppcloud.consumer.feign.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Feign header setting
 * 网关会需要 header 进行认证信息。内部invoke不需要重写 header
 *
 * 注意：如果异步请求 接口，那么会获取不到 header 信息。
 * 异步请求方法外：RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
 * 异步请求方法中： RequestContextHolder.setRequestAttributes(attributes);
 * 才可以获取到 header 信息
 */
@Configuration
public class FeignHeadersInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request = getHttpServletRequest();
        if (Objects.isNull(request)) {
            return;
        }
        Map<String, String> headers = getHeaders(request);
        if (headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                if (!"transfer-encoding".equals(entry.getKey())) {
                    // 把请求过来的header请求头 原样设置到feign请求头中
                    // 包括token
                    requestTemplate.header(entry.getKey(), entry.getValue());
                }
            }
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enums = request.getHeaderNames();
        while (enums.hasMoreElements()) {
            String key = enums.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            // 这种方式获取的HttpServletRequest是线程安全的
            return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        } catch (Exception e) {

            return null;
        }
    }
}
